package org.lanqiao.service.impl;

import org.lanqiao.dao.AdminDao;
import org.lanqiao.entity.Admin;
import org.lanqiao.service.AdminService;
import org.lanqiao.util.Result;
import org.lanqiao.util.SessionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminDao adminDao;

    /**
     * @Author 王宇
     * @Description //TODO 判断超管的账号密码是否正确
     * @Date 2019/05/22 17:15
     * @Param [adminAccout, adminPassword]
     * @return org.lanqiao.entity.Admin
     */
    @Override
    public Result getAdmin(String adminAccout, String adminPassword) {
        Result result = new Result();
        try {
            Admin admin = adminDao.getAdmin(adminAccout, adminPassword);
            if(admin != null){
                if(SessionListener.sessionMap.get(adminAccout) != null){
                    return Result.defeated("账户已登陆");
                }else{
                    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                    HttpSession session = request.getSession();
                    session.setAttribute(adminAccout, adminAccout);
                    SessionListener.sessionCreated(session, adminAccout);
                    result.setCode(0);
                    result.setMsg("账号密码输入正确,登录成功");
                    result.setData(admin);
                }
            }else{
                result.setCode(1);
                result.setMsg("账号密码输入错误,请重新输入！");
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Author 王宇
     * @Description //TODO 超管退出
     * @Date 2019/06/17 17:08
     * @Param [userEmail]
     * @return org.lanqiao.util.Result
     */
    public Result adminExit(String adminAccout) {
        SessionListener.sessionDestroyed(adminAccout);
        return Result.ok("");
    }

}
